package controllers;

import models.User;

import com.feth.play.module.pa.PlayAuthenticate;
import com.feth.play.module.pa.providers.password.UsernamePasswordAuthProvider;
import com.feth.play.module.pa.user.AuthUser;

import play.Routes;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Http.Context;
import play.mvc.Http.Session;
import play.mvc.Result;
import security.ConsoleUsernamePasswordAuthProvider;
import security.ConsoleUsernamePasswordAuthProvider.ConsoleLogin;
import views.html.*;

import play.Play;
import jsmessages.JsMessages;

public class Application extends Controller {

	final static JsMessages messages = new JsMessages(Play.application());

	public static final String FLASH_SUCCESS_KEY = "success";
	public static final String FLASH_ERROR_KEY = "error";

	public static final String ROLE_ADMIN = "admin";
	public static final String ROLE_USER = "user";

	public static Result index() {
		return ok(index.render("Welcome to " + play.Play.application().configuration().getString("application.name") + "!"));
	}

	public static Result login() {
		final Context context = ctx();
		if (context.flash().containsKey(ConsoleUsernamePasswordAuthProvider.ERROR_LOGIN_USER_NOT_FOUND)) {
			context.flash().remove(ConsoleUsernamePasswordAuthProvider.ERROR_LOGIN_USER_NOT_FOUND);
			context.flash().put(FLASH_ERROR_KEY, "Invalid login credentials");
		}
		return ok(login.render(ConsoleUsernamePasswordAuthProvider.FORM_LOGIN));
	}

	public static Result doLogin() {
		com.feth.play.module.pa.controllers.Authenticate.noCache(response());
		final Form<ConsoleLogin> form = ConsoleUsernamePasswordAuthProvider.FORM_LOGIN.bindFromRequest();
		if (form.hasErrors()) {
			return badRequest(login.render(form));
		} else {
			return UsernamePasswordAuthProvider.handleLogin(ctx());
		}
	}

	public static Result authenticationDenied(String provider) {
		flash(FLASH_ERROR_KEY, "You need to accept the OAuth connection in order to use this website!");
		return redirect(routes.Application.login());
	}

	public static User getLocalUser(final Session session) {
		final AuthUser authUser = PlayAuthenticate.getUser(session);
		final User user = User.findByAuthUserIdentity(authUser);
		return user;
	}

	public static Result javaScriptRoutes() {
		response().setContentType("application/javascript");
		return ok(Routes.javascriptRouter("jsRoutes", controllers.routes.javascript.Configurations.getConfigContentRaw()));
	}

	public static Result javaScriptMessages() {
		return ok(messages.generate("window.Messages")).as("application/javascript");
	}

}
